package com.binance.rabbitmq.policy.impl;

import com.binance.rabbitmq.config.DefaultConfig;
import com.binance.rabbitmq.policy.RecovererPolicy;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * Created by robin.wu on 2018/12/3.
 */
public class DeadLetterRecovererPolicy implements RecovererPolicy {

    private static final String X_RECOVERER_COUNT = "x_recoverer_count";

    private static final Integer DEFAULT_THRESHOLD = 3;

    @Autowired
    private DefaultConfig defaultConfig;

    @Override
    public boolean recoverable(Message message) {
        Map<String, Object> headers = message.getMessageProperties().getHeaders();
        int recovererCount = 0;
        if (headers.containsKey(X_RECOVERER_COUNT)) {
            recovererCount = (int) headers.get(X_RECOVERER_COUNT);
        }
        int threshold = defaultConfig.getDeadLetterConfig().getThreshold() != null ? defaultConfig.getDeadLetterConfig().getThreshold(): DEFAULT_THRESHOLD;
        if (threshold > recovererCount) {
            headers.put(X_RECOVERER_COUNT, ++recovererCount);
            return true;
        }
        return false;
    }
}
